<template>
    <div class="app-container d-flex h-100">
        <div style="width: 50%" class="pr-10 h-100">
            <el-radio-group v-model="buttonType" v-show="!pageType">
                <el-radio-button label="地下饮用水源地"></el-radio-button>
                <el-radio-button label="地表饮用水源地"></el-radio-button>
            </el-radio-group>
            <el-upload drag :action="uploadFileUrl" :headers="headers" :show-file-list="false"  :on-success="fillhttpFn" class="upload-box py-10">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">
                    <div>将文件拖到此处，或<em>点击上传</em></div>
                    <div style="color: red;">只能上传excel文件，且不超过20M</div>
                </div>
            </el-upload>
            <div class="bg-white py-10">
                <el-form ref="form" :model="form" inline label-width="80px" size="small">
                    <el-form-item label="工作表">
                        <el-select v-model="form.sheetName" placeholder="请选择工作表">
                            <el-option v-for="item in sheetList" :key="item.sheetNum" :label="item.sheetName" :value="item.sheetName">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item >
                        <el-button type="primary" @click="importExcelSheet">导入</el-button>
                        <el-button type="warning" @click="download">模板下载</el-button>
                    </el-form-item>
                </el-form>
                <img src="./daorushuoming.png" width="100%" alt="">
            </div>
        </div>
        <div style="width: 50%" class="pl-10 h-100">
            <el-table :data="data" border style="width: 100%">
                <el-table-column prop="title" label="未入库数据" >
                    <template #default="{ row }">
                        <a href="#" style="font-weight: bold;color: #307eff;" @click.prevent="handleOpen(row)">{{ row.title }}</a>
                    </template>
                </el-table-column>
                <el-table-column prop="dataStateCode" label="数据状态" width="150px">
                    <template #default="{ row }">
                        {{tabledataMap[row.dataStateCode]|| ''}}
                    </template>
                </el-table-column>
                <el-table-column prop="prop" label="操作"  width="100xp">
                    <template #default="{ row }">
                        <el-button size="mini" type="text" @click="handleDelete(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <el-dialog :title="'详情'" :visible.sync="dialogVisible" width="1200px" append-to-body>
            <el-table :data="detailTableData" style="width: 100%">
                <template v-for="value in detailTableTitle">
                    <el-table-column :key="value.field" :prop="value.field" :label="value.title">
                    </el-table-column>
                </template>
            </el-table>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">数据入库</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
    import {excelFileShell,surfaceWaterListData,busDataTempdataReportID,deleteBusTempdataByReportId,importTemplateData,dataReportingAndSavingsyd,dataReportingAndSaving} from './api'
    import { getToken } from "@/utils/auth"
    export default {
        props: {
            pageType:{
                default: '',
                type: String
            }
        },

        data() {
            return {
                data: [],
                uploadFileUrl: process.env.VUE_APP_BASE_API + '/manualData/excelFileShell', // 上传文件服务器地址
                headers: {
                    Authorization: "Bearer " + getToken(),
                },
                // action:'',
                buttonType:"地下饮用水源地",
                btnTypeMap:{
                    "地下饮用水源地":"CBF8",
                    "地表饮用水源地":"CBF1",
                    "手工地表水": "CBN"

                },
                tabledataMap:{
                    '0':'待入库',
                    '1':'正在入库',
                },
                form:{},
                file:null,
                sheetList:[],
                dialogVisible:false,
                detailTableData:[],
                detailTableTitle:[],
                startInDbId:'',

            };
        },
        created() {
            if(this.pageType) {
                this.buttonType = "手工地表水";
            }
            this.getList();
        },
        methods: {
            async getList(){
                let datatype = '2';
                if(this.pageType) {
                    datatype = '1';
                }
                let res = await busDataTempdataReportID({datatype})
                this.data = res.data;
            },
            async fillhttpFn(res, file) {
                console.log(res,file);
                this.file = file.raw;
                this.sheetList = res.data;
            },
            async handleOpen(row){
                if(this.dialogVisible){
                    return;
                }
                if(row.dataStateCode == '1'){
                    this.$message.warning('正在入库中，请勿重复导入')
                    return
                }
                let reportId = row.reportId;
                this.startInDbId = reportId;
                let res = await importTemplateData({reportId})
                this.detailTableTitle = res.title.filter(item=>item.isShow == '1');
                this.detailTableData = res.data;
                this.dialogVisible = true;
            },
            async submitForm(){
                //reportID
                let apiFn = this.pageType ? dataReportingAndSaving : dataReportingAndSavingsyd;
                let res =  await apiFn({reportId:this.startInDbId})
                if(res.code == 200){
                    this.$message.success(res.msg)
                }
                this.dialogVisible = false;
                this.startInDbId = '';
            },
            async handleDelete(row){
                let reportId = row.reportId;
                let res = await this.$confirm(`确定删除吗？`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    return true
                }).catch(() => {
                    return false
                });
                if(res){
                    await deleteBusTempdataByReportId({reportId});
                    this.getList();
                }
            },  
            async importExcelSheet(){
                if(!this.file || !this.form.sheetName){
                    this.$message.warning('请选择文件或者选择sheet')
                    return 
                }
               let prop = this.btnTypeMap[this.buttonType];
               let file = this.file;
               let sheetName = this.form.sheetName;
               const formData = new FormData();
               formData.append('file', file);
               formData.append('sheetName', sheetName);
               formData.append('prop',prop)
               await surfaceWaterListData(formData)
            //    .then(res=>{
            //        console.log(res);
            //        this.data = res.data;
            //    })
               await this.getList();
            },  
            download(){
                let fileNameMap = {
                    "地下饮用水源地":"地下饮用水源地实验数据导入模板.xlsx",
                    "地表饮用水源地":"地表饮用水源地实验数据导入模板.xlsx",
                    "手工地表水": "地表水实验室数据导入模板.xlsx"
                }
                // 根据当前选择的按钮类型确定下载的文件路径
                const fileName = fileNameMap[this.buttonType];
                
                // 构建文件路径 - public目录下的文件可以直接访问
                let baseUrl = process.env.ENV === "development" ? '../../../../public/otherFile':'/otherFile';
                const filePath = `${baseUrl}/${fileName}`;
                
                // 创建下载链接
                const link = document.createElement('a');
                link.href = filePath;
                link.download = fileName;
                link.style.display = 'none';
                
                // 添加到页面并触发下载
                document.body.appendChild(link);
                link.click();
                
                // 清理
                document.body.removeChild(link);
            }

        }
    }
</script>
<style lang="scss" scoped>
.upload-box{
    width: 100%;
    ::v-deep .el-upload{
        width: 100% !important;
        .el-upload-dragger {
            width: 100% !important;
        }
    }
    // border: 1px dashed #d9d9d9;
    // border-radius: 6px;
}
.bg-white{ 
    background-color: #fff;
}

</style>